import React, { Component, PureComponent } from "react";
import PropTypes from "prop-types";
import "./Loadmore.module.less";

export default class Loadmore extends PureComponent {
  loadmoreRef = null;

  distance = 0;

  constructor(props) {
    super(props);
    this.state = { status: "more", targetDistance: 30 };
    this.handleLoadmore = this.handleLoadmore.bind(this);
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.status !== undefined) {
      return {
        status: nextProps.status,
      };
    }
    return null;
  }

  componentDidMount() {
    this.handleLoadmore();
    window.addEventListener("scroll", this.handleLoadmore);
  }

  componentWillUnmount() {
    window.removeEventListener("scroll", this.handleLoadmore);
  }

  /**
   * 处理距底距离的判断
   * @param {*} e
   */
  handleLoadmore(e) {
    let scrollTop =
      (document.documentElement && document.documentElement.scrollTop) ||
      document.body.scrollTop;
    let scrollHeight =
      (document.documentElement && document.documentElement.scrollHeight) ||
      document.body.scrollHeight;
    let clientHeight =
      document.documentElement.clientHeight || window.innerHeight;

    this.distance = scrollHeight - Math.ceil(scrollTop + clientHeight);
    if (this.distance < this.state.targetDistance) {
      this.props.onLoadmore && this.props.onLoadmore();
    }
  }

  render() {
    let { status } = this.state;
    let { renderMore, renderNomore, renderLoading } = this.props;

    let moreContent = null;
    if (status === "loading")
      moreContent = renderLoading ? renderLoading() : <div>加载中...</div>;
    else if (status === "nomore")
      moreContent = renderNomore ? renderNomore() : <div>没有更多了</div>;
    else moreContent = renderMore ? renderMore() : <div>加载更多</div>;

    return (
      <div
        className="b-loadmore"
        ref={(v) => {
          this.loadmoreRef = v;
        }}
      >
        {moreContent}
      </div>
    );
  }
}
Loadmore.propTypes = {
  onLoadmore: PropTypes.func,
  renderLoading: PropTypes.func,
  renderMore: PropTypes.func,
  renderNomore: PropTypes.func,
};
